<template>
  <div class="">
    <el-dialog v-model="dialogFormVisible" :title="title" width="1000" destroy-on-close :close-on-click-modal="closeOnClickModal">
      <el-row>
        <el-col :span="6">
          <div>
            <el-input v-model="searchCategory" placeholder="选择分类" :prefix-icon="Search" @change="queryAllCategory" clearable/>
          </div>
          <div style="margin-top: 10px;">
            <el-tree
              style="max-width: 600px"
              :data="categoryData"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span>{{ data.categoryName }}</span>
                  <el-dropdown placement="bottom">
                    <el-icon><MoreFilled /></el-icon>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="createCategory">添加分类</el-dropdown-item>
                        <el-dropdown-item @click="updateCategory(data.id)" v-if="data.pid !== 0">编辑分类</el-dropdown-item>
                        <el-dropdown-item @click="removeCategory(data.id)" v-if="data.pid !== 0">删除分类</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </span>
              </template>
            </el-tree>
          </div>
        </el-col>
        <el-col :span="18">
          <div class="btn">
            <div class="btn-left">
              <el-button type="primary" @click="useSelectImg">使用选中图片</el-button>
              <el-upload
                ref="uploadRef"
                class="upload-demo"
                :action="action"
                :show-file-list="false"
                :on-success="uploadSuccess"
                :data="paramsData"
              >
              <template #trigger>
                <el-button :icon="Upload" style="margin-right: 15px;margin-left: 15px;" @click="submitUpload"/>
              </template>
              </el-upload>
              <el-tree-select
                v-model="pid"
                :data="categoryData"
                check-strictly
                :render-after-expand="false"
                :props="{ label: 'categoryName', children: 'children', value: 'id'}"
                style="width: 240px"
                placeholder="图片移动至"
                @change="currentChange"
              />
            </div>
            <div class="btn-right">
              <el-radio-group v-model="tabPosition" style="margin-bottom: 30px" @change="radioGroupChange">
                <el-radio-button value="img">图片</el-radio-button>
                <el-radio-button value="video">视频</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="img_list">
            <div class="img_index" :style="pitchOnImg" v-for="(item, index) in imgDatas" :key="index">
              <span v-show="backgroundDatas.includes(index)" class="num_badge">{{ item.count }}</span>
              <el-image 
                :style="{width: '90px', height: '90px', background: '#aaa9a9', border: backgroundDatas.includes(index) ? '2px solid blue' : ''}" 
                :src="item.url" 
                fit="cover" @click="handleImg(item, index)"/>
                <div class="img_title">{{ item.fileName }}</div>
            </div>
          </div>
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[18, 36, 72, 144]"
            size="default"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
      <upload-category ref="uploadCategoryRef" @refreshDataList="queryAllCategory"></upload-category>
    </el-dialog>
  </div>
</template>

<script setup>
  import { reactive, ref } from 'vue'
  import { Search, Upload } from '@element-plus/icons-vue'
  import { tableList, tableDetailList, moveImgToCategory, deleteCategory } from '~/api/upload/upload.js'
  import UploadCategory from './upload-category.vue'
  import { showMessage } from '~/utils/my-notification.js'
  import { BASE_URL } from '~/utils/request'
  import { ElLoading } from 'element-plus'

  const dialogFormVisible = ref(false)
  const title = ref('上传图片')
  const closeOnClickModal = ref(false)
  const searchCategory = ref('')
  const categoryData = ref([])
  const tabPosition = ref('img')
  const uploadCategoryRef = ref(null)
  const pid = ref()
  const uploadRef = ref()
  const categoryId = ref(1)
  const imgDatas = ref([])
  const currentPage = ref(1)
  const pageSize = ref(18)
  const background = ref(false)
  const disabled = ref(false)
  const total = ref(0)
  const multipleSelection = ref([])
  const pitchOnImg = ref()
  const backgroundDatas = ref([]) // 选中时的数据
  const num = ref(0) // 点击图片时的下标数字
  const imgs = ref([]) // 选中的图片列表
  const action = BASE_URL + '/api/admin/upload/public'
  const isMultiple = ref(false) // 是否可以选择多个
  const loadingInstance = ref({}) // 上传加载中...

  // 查询所有分类
  queryAllCategory()

  /**
   * 初始化
   * @param isMultipleChoice 是否可以多选，false：不可以；true：可以；
   * @param choiceType 选择类型，img:图片；video：视频；默认img
   */
  function init(isMultipleChoice, choiceType = 'img') {
    dialogFormVisible.value = true
    isMultiple.value = isMultipleChoice
    tabPosition.value = choiceType
    num.value = 0
    imgs.value = []
    backgroundDatas.value = []
    // 查询全部图片
    quseryAllImg(categoryId.value)
  }
  function handleNodeClick(data) {
    quseryAllImg(data.id)
  }
  // 查询所有分类
  function queryAllCategory() {
    tableList(searchCategory.value).then(res => {
      if(res && res.data.code === 200) {
        categoryData.value = res.data.data
      }
    })
  }
  // 查询全部图片
  function quseryAllImg(categoryId) {
    tableDetailList(currentPage.value, pageSize.value, { categoryId: categoryId, type: tabPosition.value }).then(res => {
      if(res && res.data.code === 200) {
        imgDatas.value = res.data.data.records
        total.value = res.data.data.total
      }
    })
  }
  // 图片和视频的相互切换
  function radioGroupChange(value) {
    tabPosition.value = value
    quseryAllImg(categoryId.value)
  }
  // 创建分类
  function createCategory() {
    if(uploadCategoryRef.value) {
      uploadCategoryRef.value.initUpload()
    }
  }
  // 编辑分类
  function updateCategory(categoryId) {
    if(uploadCategoryRef.value) {
      uploadCategoryRef.value.initUpload(categoryId)
    }
  }
  // 删除分类
  function removeCategory(categoryId) {
    deleteCategory(categoryId).then(res => {
      if(res && res.data.code === 200) {
        showMessage('删除成功!')
        queryAllCategory()
      } else {
        showMessage(res.data.data, 'error')
      }
    })
  }
  // 上传
  function submitUpload() {
    loadingInstance.value = ElLoading.service({ fullscreen: true, text: '上传中...' })
    uploadRef.value.submit()
  }
  // 上传成功
  function uploadSuccess(response, uploadFile, uploadFiles) {
    if(response && response.code === 200) {
      showMessage('上传成功!')
      loadingInstance.value.close()
      quseryAllImg(categoryId.value)
    } else {
      showMessage('上传失败', 'error')
    }
  }
  // 上传时附带的参数
  function paramsData() {
    const data = {
      categoryId: categoryId.value,
      type: tabPosition.value === 'img' ? 0 : 1
    }
    return data;
  }

  // 多选
  function handleSelectionChange(val) {
    multipleSelection.value = val
  }
  const handleSizeChange = (val) => {
    console.log(`${val} items per page`)
  }
  const handleCurrentChange = (val) => {
    currentPage.value = val
    quseryAllImg(categoryId.value)
  }

  // 点击图片
  function handleImg(item, index) {
    // 判断如果index在backgroundDatas中，就把index从数组中删除，否则就添加
    if(isMultiple.value) {
      // 允许多选
      if(backgroundDatas.value.includes(index)) {
        num.value --
        imgDatas.value[index].count = 0
        // 重新赋值
        var imgCounts = []
        imgDatas.value.forEach((item, i) => {
          if(item.count !== 0) {
            imgCounts.push(i)
          }
        });
        for(var a=0;a<num.value;a++) {
          for(var b=0;b<imgCounts.length;b++) {
            if(a === b) {
              imgDatas.value[imgCounts[b]].count = a + 1
              break;
            }
          }
        }
        backgroundDatas.value = backgroundDatas.value.filter(item => item !== index)
        imgs.value = imgs.value.filter(data => data.url !== item.url)
      } else {
        num.value ++
        imgDatas.value[index].count = num.value
        backgroundDatas.value.push(index)
        imgs.value.push(item)
      }
    } else {
      // 不允许多选
      num.value = 1
      backgroundDatas.value = []
      imgs.value = []
      imgDatas.value[index].count = num.value
      backgroundDatas.value.push(index)
      imgs.value.push(item)
    }
  }

  const emit = defineEmits(['selectImgUrl'])
  // 使用选中的图片
  function useSelectImg() {
    if(imgs.value.length <= 0) {
      showMessage('请选中图片!', 'error')
      return;
    }
    if(isMultiple.value) {
      // 允许多选
      emit('selectImgUrl', imgs.value)
    } else {
      // 不允许多选
      const selectImg = imgs.value[0]
      emit('selectImgUrl', selectImg)
    }
    dialogFormVisible.value = false
  }

  // el-tree-select节点选中变化时触发
  function currentChange(data) {
    if(imgs.value.length <= 0) {
      showMessage('请先选择要移动的图片!', 'error')
      return
    }
    var ids = []
    imgs.value.forEach(item => {
      ids.push(item.id)
    });
    // 进行移动
    moveImgToCategory({ids: ids, categoryId: data}).then(res => {
      if(res && res.data.code === 200) {
        showMessage('移动成功!')
      }
    })
  }

  // 将方法暴露给父组件
  defineExpose({
    init
  })
</script>
<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .btn {
    margin-left: 10px;
    display: flex;
    justify-content: flex-end;
  }
  .btn-left {
    display: flex;
  }
  .btn-right {
    margin-left: auto;
  }

  .img_list {
    margin-left: 10px;
    margin-bottom: 10px;
    display: flex;
    flex-wrap: wrap;
  }
  .img_index {
    width: 90px;
    height: 120px;
    box-sizing: border-box;
    margin: 10px;
    cursor: pointer;
    position: relative;
  }
  .img_title {
    text-align: left;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 90px;
  }
  .num_badge {
    position: absolute;
    bottom: 30px;
    display: inline-block;
    min-width: 20px;
    height: 20px;
    border-radius: 10px;
    background: blue;
    font-size: 14px;
    text-align: center;
    color: #fff;
    line-height: 20px;
    z-index: 9;
  }
</style>
